package org.singledog.form.builder.parser.freemarker.directions;

import freemarker.core.Environment;
import freemarker.template.*;
import freemarker.template.utility.DeepUnwrap;
import org.singledog.form.builder.parser.freemarker.freemarker.FreeMarkerConfiguration;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

public class BuilderIncludeDirectiveModel implements TemplateDirectiveModel {
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        if (CollectionUtils.isEmpty(params)) {
            throw new TemplateModelException(
                    "This directive needs parameters.");
        }

        TemplateModel value = (TemplateModel) params.get("path");
        if (value == null) {
            throw new TemplateModelException(
                    "This directive needs a path parameter.");
        }

        Object path = DeepUnwrap.unwrap(value);

        Writer out = env.getOut();
        FreeMarkerConfiguration.getTemplate(String.valueOf(path)).process(params, out);
        if (body != null) {
            body.render(out);
        }
    }
}
